package com.liwentao.seckill.controller;

import com.liwentao.seckill.entity.User;
import com.liwentao.seckill.entity.vo.GoodsVo;
import com.liwentao.seckill.result.R;
import com.liwentao.seckill.service.IGoodsService;
import com.liwentao.seckill.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Map;

@Controller
@RequestMapping("/seckill/goods")
@Api(value = "商品管理",tags = "商品")
public class GoodsController {
    @Resource
    private IUserService userService;
    @Resource
    private IGoodsService goodsService;

    @PostMapping("/tolist")
    @ApiOperation(value = "tolist",tags = "进入商品页面")
    public String toList(Model model, User user){
        model.addAttribute("user", user);
        model.addAttribute("goodsList", goodsService.findGoodsVo());
        System.out.println(goodsService.findGoodsVo());
        return "goodslist";
    }

    @GetMapping("/toDetail/{goodsId}")
    @ApiOperation(value = "toDetail",tags = "进入商品页面")
    @ResponseBody
    public R toDetail(Model model, User user, @ApiParam(name ="goodsId" ,value = "商品id",required = true)@PathVariable Long goodsId){
        model.addAttribute("user", user);
        R goodsVoByGoodsId = goodsService.findGoodsVoByGoodsId(goodsId);
        Map<String, Object> data = goodsVoByGoodsId.getData();
        GoodsVo goodsVo = (GoodsVo)data.get("goodsVo");
        LocalDateTime startDate = goodsVo.getStartDate();
        LocalDateTime endDate = goodsVo.getEndDate();
        LocalDateTime nowDate = LocalDateTime.now();
        System.out.println("现在的时间："+nowDate);
        System.out.println("开始的时间："+startDate);
        System.out.println("结束的时间："+endDate);
        int seckillStatue=0;
        String remainSeconds="";
        //秒杀未开始
        if (nowDate.isBefore(startDate)){
            Duration between = Duration.between(nowDate, startDate);
            long l3 = between.toMillis()/1000;
            int n=(int) (nowDate.getSecond()-startDate.getSecond());
            System.out.println(n);
            remainSeconds=l3+"秒";
        }else if (nowDate.isAfter(endDate)){
            //秒杀已结束
            seckillStatue=2;
            remainSeconds="-1";
        }else{
            //秒杀进行中
            seckillStatue=1;
            remainSeconds="0";
        }
        model.addAttribute("goodsVo", goodsVo);
        model.addAttribute("seckillStatue", seckillStatue);
        goodsVoByGoodsId.data("seckillStatue", seckillStatue);
        goodsVoByGoodsId.data("remainSeconds", remainSeconds);
        return goodsVoByGoodsId;
    }
}
